<!-- 页面 -->
<template>
  <div class="user-list">
    
    <el-table :data="paginatedUserList" border style="width: 100%" class="center-table">
      <el-table-column prop="name" label="用户名" align="center">
        <template #default="scope">
          <span class="ellipsis" :title="scope.row.name">{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" align="center">
        <template #default="scope">
          <span class="ellipsis" :title="scope.row.email">{{ scope.row.email }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="电话" align="center"> </el-table-column>
      <el-table-column prop="address" label="地址" align="center"> </el-table-column>
      <el-table-column prop="isManager" label="是否管理员" align="center">
        <template #default="scope">
          <span class="ellipsis" :title="scope.row.isManager">
            <span v-if="scope.row.isManager == 1">是</span>
            <span v-else>否</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300" align="center">
        <template #default="scope">
          <el-button v-if="isAdmin" size="mini" @click="openEditDialog(scope.row)">
            编辑
          </el-button>
          <el-button size="mini" @click="openDetailsDialog(scope.row)">详情</el-button>
          <el-button
            v-if="isAdmin"
            size="mini"
            @click="editOpenEditDialog(scope.row)"
            >修改密码</el-button
          >
          <el-button
            v-if="isAdmin"
            v-permission="'delete_info'"
            size="mini"
            type="danger"
            @click="deleteRow(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页和添加按钮同一行 -->
    <div class="pagination-bar">
      <el-pagination
        class="pagination"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
      <el-button
        v-if="isAdmin"
        type="primary"
        class="button add-btn"
        @click="openAddDialog"
      >
        添加用户
      </el-button>
    </div>

    <!-- 添加用户弹出层 -->
    <el-dialog :visible.sync="addDialogVisible" title="添加用户" width="700px">
      <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="100px">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="addForm.phone" placeholder="请输入电话"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="addForm.address" placeholder="请输入地址"></el-input>
        </el-form-item>
        <el-form-item label="是否管理员" prop="isManager">
          <el-select v-model="addForm.isManager" placeholder="请选择是否管理员">
            <el-option label="是" value="1">是</el-option>
            <el-option label="否" value="2">否</el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddUser">保存</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户弹出层 -->
    <el-dialog :visible.sync="editDialogVisible" title="编辑用户" width="700px">
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入电话"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="editForm.address" placeholder="请输入地址"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditUser">保存</el-button>
      </span>
    </el-dialog>

    <!-- 详情弹出层 -->
    <el-dialog :visible.sync="detailsDialogVisible" title="用户详情" width="700px">
      <el-form :model="detailsForm" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="detailsForm.name" disabled />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="detailsForm.email" disabled />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="detailsForm.phone" disabled />
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="detailsForm.address" disabled />
        </el-form-item>
        <el-form-item label="是否管理员">
          <span v-if="detailsForm.isManager == 1" class="span">是</span>
          <span v-else class="span">否</span>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailsDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  usergetToolList,
  insertgetToolList,
  updategetToolList,
  deletegetToolList,
  editGetToolList
} from "@/api/user/index.js";
import dayjs from "dayjs"; // 确保正确引入 dayjs
export default {
  data() {
    return {
      userList: [], // 用户列表数据
      addDialogVisible: false, // 控制添加用户弹出层显示
      editDialogVisible: false, // 控制编辑用户弹出层显示
      detailsDialogVisible: false, // 控制详情弹出层显示
      addForm: {
        name: "",
        password: "",
        email: "",
        phone: "",
        address: "",
        birthday: "",
        isManager: "", // 默认值
      },
      editForm: {}, // 编辑用户表单数据
      detailsForm: {}, // 详情弹出层数据
      addRules: {
        name: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
      editRules: {
        name: [{ required: true, message: "请输入用户名", trigger: "blur" }],
      },
      roleTypeOptions: [
        // 下拉列表选项
        { label: "是", value: "1" },
        { label: "否", value: "2" },
      ],
      total: 0,
      pageSize: 10,
      currentPage: 1,
    };
  },
  mounted() {
    this.usergetTool(); // 调用获取用户列表的方法
    
    // 调试isAdmin状态
    console.log(
      "用户列表组件挂载，isAdmin:",
      this.$store.getters["permissions/isAdmin"],
      "isManager:", 
      this.$store.state.permissions.isManager
    );
  },
  computed: {
    ...mapGetters("permissions", ["getUsername", "isAdmin"]),
    paginatedUserList() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.userList.slice(start, end);
    },
  },
  methods: {
    editOpenEditDialog(row) {
      let id = row.id; // 获取用户ID
      this.$prompt("请输入新密码", "修改密码", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/,
        inputErrorMessage: "密码必须包含字母和数字，并且至少6位",
      })
        .then(({ value }) => {
          console.log("新密码:", value);
          const userData = { id, password: value };

          // 调用修改密码接口
          editGetToolList(userData)
            .then(() => {
              this.$message.success("密码修改成功");
            })
            .catch(() => {
              this.$message.error("密码修改失败");
            });
        })
        .catch(() => {
          this.$message.info("取消修改");
        });
    },
    async usergetTool() {
      try {
        const response = await usergetToolList();
        this.userList = response.data;
        this.total = this.userList.length;
        console.log("获取用户列表成功:", this.userList);
      } catch (error) {
        console.error("获取用户列表失败:", error);
      }
    },
    openAddDialog() {
      this.addDialogVisible = true; // 打开添加用户弹出层
      if (this.$refs.addFormRef) {
        this.$refs.addFormRef.resetFields(); // 重置表单
      }
    },
    async handleAddUser() {
      if (this.addForm.birthday) {
        this.addForm.birthday = dayjs(this.addForm.birthday).format(
          "YYYY-MM-DD HH:mm:ss"
        );
      }
      try {
        await this.$refs.addFormRef.validate(); // 验证表单
        const response = await insertgetToolList(this.addForm); // 调用添加用户接口
        console.log("添加用户成功:", response);
        this.$message.success("用户添加成功");
        this.addDialogVisible = false; // 关闭弹出层
        this.usergetTool(); // 刷新用户列表
      } catch (error) {
        console.error("添加用户失败:", error);
        this.$message.error("用户添加失败，请稍后再试");
      }
    },
    openEditDialog(row) {
      this.editForm = { ...row }; // 数据回显
      this.editDialogVisible = true; // 打开编辑用户弹出层
    },
    async handleEditUser() {
      if (this.editForm.birthday) {
        this.editForm.birthday = dayjs(this.editForm.birthday).format(
          "YYYY-MM-DD HH:mm:ss"
        );
      }
      try {
        // 只发送后端需要的字段，避免多余字段导致 400 错误
        const payload = {
          id: this.editForm.id,
          name: this.editForm.name,
          email: this.editForm.email,
          birthday: this.editForm.birthday,
          phone: this.editForm.phone,
          address: this.editForm.address,
          isManager: this.editForm.isManager,
        };
        await this.$refs.editFormRef.validate(); // 验证表单
        const response = await updategetToolList(payload); // 调用更新用户接口
        console.log("编辑用户成功:", response);
        this.$message.success("用户编辑成功");
        this.editDialogVisible = false; // 关闭弹出层
        this.usergetTool(); // 刷新用户列表
      } catch (error) {
        console.error("编辑用户失败:", error);
        this.$message.error("用户编辑失败，请稍后再试");
      }
    },
    openDetailsDialog(row) {
      this.detailsForm = { ...row }; // 数据回显
      this.detailsDialogVisible = true; // 打开详情弹出层
    },
    async deleteRow(id) {
      try {
        await this.$confirm("此操作将永久删除该条记录, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        const response = await deletegetToolList(id); // 调用删除接口
        console.log("删除用户成功:", response);
        this.$message.success("用户删除成功");
        this.usergetTool(); // 刷新用户列表
      } catch (error) {
        console.error("删除用户失败:", error);
        this.$message.error("用户删除失败，请稍后再试");
      }
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.currentPage = 1;
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
    },
  },
};
</script>

<style scoped>
.user-list {
  padding: 0;
}
.center-table{
  border-radius: 10px;
}
.center-table .el-table__cell {
  text-align: center; /* 确保表格内容和表头文字都居中 */
}
.dialog-footer {
  text-align: right;
}
.ellipsis {
  display: inline-block;
  max-width: 150px; /* 设置最大宽度 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
/* 按钮去掉边框和背景色，字体白色 */
.el-button,
button {
  background: none;
  color: #fff;
  box-shadow: none;
}
/* 弹窗背景和字体色 */
.el-dialog,
.el-dialog__body,
.el-dialog__header,
.el-dialog__footer {
  background-color: #262626;
  color: #fff;
}
/* 输入框字体色 */
.el-input__inner {
  color: #fff;
  background-color: #222;
  border-color: #444;
}
/* 下拉框字体色 */
.el-select-dropdown,
.el-select-dropdown__item {
  background-color: #262626;
  color: #fff;
}
::v-deep .el-dialog__header {
  background-color: #2e2e2e !important; /* 黑色背景 */
}
::v-deep .el-dialog__header .el-dialog__title {
  color: #fff !important; /* 白色字体 */
}
::v-deep .el-dialog__body {
  background-color: #2e2e2e !important; /* 黑色背景 */
}
::v-deep .el-dialog__footer {
  background-color: #2e2e2e !important; /* 黑色背景 */
}
::v-deep .el-message-box .el-message-box__header {
  background-color: #2e2e2e !important; /* 黑色背景 */
}
::v-deep .el-dialog__body .el-form .el-form-item .el-form-item__label {
  color: #fff !important;
}
::v-deep .el-input .el-input__inner {
  background-color: #2e2e2e !important; /* 黑色背景 */
}
::v-deep .el-input__inner {
  color: #fff !important;
}
.span {
  color: #fff !important;
}
.pagination {
  text-align: right;
  flex: 1;
}
.add-btn {
  margin-left: 20px;
  margin-top: 0 !important;
}
.pagination-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 20px;
  width: 100%;
}
.el-pagination{
  width: 90%;

}
</style>
